<?php 
/*
 * Created on 2009-7-20
 *
 * Author: guobin@yizin.net
 */
require_once ("ISBN.php");
require_once ("SimpleImage.php");
class Utils {

    public static function getURI() {
    
        $land = "index.php";
        $scriptName = $_SERVER['SCRIPT_NAME'];
        $prefix = substr($scriptName, 0, strlen($scriptName) - strlen($land));
        $uri = substr($_SERVER['REQUEST_URI'], strlen($prefix) - 1);
        if (strpos($uri, "/".$land) === 0) {
            $uri = substr($uri, strlen("/".$land));
        }
        return $uri;
    }
    
    public static function isIp($str) {
    
        return preg_match("/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){4}$/", $str.".");
    }
    /*
     * This method is to judge whether $str is a E-mail address or not.
     *
     * @param string $str the variable to check
     *
     * @return bool whether $str is a right E-mail address or not.
     */
    
    public static function isEmail($str) {
    
        return preg_match("/^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$/",
             $str);
    }
    /*
     * This method is to judge whether $str is mixed by number and letter and started with a letter or not.
     *
     * @param string $str the variable to check
     *
     * @return bool whether the rules above is correct or not.
     */
    
    public static function isIdentifier($str) {
    
        if ($str == "") {
            return false;
        }
        //starts with letter
        if (!('a' <= $str[0] && $str[0] <= 'z' || 'A' <= $str[0] && $str[0] <= 'Z')) {
            return false;
        }
        //contains only letter or number
        for ($i = 0, $length = strlen($str); $i < $length; $i++) {
            if (!('a' <= $str[$i] && $str[$i] <= 'z' || 'A' <= $str[$i] && $str[$i] <= 'Z' || ord('0') <= ord($str[$i]) &&
                 ord($str[$i]) <= ord('9'))) {
                return false;
            }
        }
        return true;
    }
    /*
     * Check to see if the entered isbn is valid and return
     * true or false depending.
     * I'm not even going to try to claim copyright for such
     * a simple thing. Do what you will with it.
     * 8-) Keith Nunn, kapn@anglican.ca
     */
    
    public static function isISBN($isbn) {
    
        $bool = false;
        $ISBN = new ISBN();
        $isbnType = $ISBN->getType($isbn);
        
        if ($isbnType < 1) {
        } else if ($isbnType == 10) {
            $bool = $ISBN->validate10($isbn);
        } else if ($isbnType == 13) {
            $bool = $ISBN->validate13($isbn);
        }
        return $bool;
        
    }
    
    public static function isBlank($str) {
    
        return $str ? trim($str) === "" : true;
    }
    
    public static function isDateTime($time) {
    
        if (!$time) {
            return false;
        }
        $result = array();
        preg_match("/^(\d{4}|\d{2})[-.\/\s]?(\d{1,2})[-.\/\s]?(\d{1,2})/", $time, $result);
        return checkdate($result[2], $result[3], $result[1]);
    }
    
    public static function loadSegment($file) {
    
        ob_start();
        include ($file);
        $temp = ob_get_contents();
        ob_end_clean();
        return $temp;
    }
    
    public static function saveImage($resourceBase, $serial, $image, $widthList) {
    
        $imageFileName = array();
        $fileName = intval(time(), 16);
        if (isset($image) && $image['size'] != 0) {
            if (is_dir($resourceBase)) {
                $path = $resourceBase.DIRECTORY_SEPARATOR.Utils::getPathBySerial($serial);
                try {
                    if (!file_exists($path)) {
                        Utils::recur_mkdirs($path);
                    }
                    $imageResizer = new SimpleImage();
                    $imageResizer->load($image['tmp_name']);
                    $imageResizer->save($path.DIRECTORY_SEPARATOR.'r'.$fileName.'.'.Utils::fileext($image['name']));
                    foreach (array_keys($widthList) as $key) {
                        $value = $widthList[$key];
                        
                        switch ($key) {
                            case "default":
                                array_push($imageFileName, $fileName.'.'.Utils::fileext($image['name']));
                                break;
                            case "small":
                                $fileName = "s".$fileName;
                                break;
                            case "large":
                                $fileName = "l".$fileName;
                                break;
                        }
                        $imageResizer->resizeToWidth($value);
                        $imageResizer->save($path.DIRECTORY_SEPARATOR.$fileName.'.'.Utils::fileext($image['name']));
                        
                    }
                }
                catch(exception $e) {
                    echo $e->getmessage();
                }
            }
        }
        return $imageFileName[0];
    }
    
    public static function pageNav($count, $page, $size, $url) {
    
        $max = 4;
        if ($count <= $size) {
            return "";
        }
        $maxPage = floor(($count - 1) / $size + 1);
        if ($page < 1 || $page > $maxPage) {
            $page = 1;
        }
        $rv = '<div class="pagination">';
        $rv .= ($page > 1) ? "<a class=\"plain\" href=\"".preg_replace("/#{page}/mi", $page - 1, $url)."\">Prev</a> " : "";
        for ($i = 1; $i <= $maxPage; $i++) {
            if ($i > 1 && $i < $page - $max) {
                $rv .= "<span class=\"plain\"> ... </span>";
                $i = $page - $max;
            }
            if ($i > $page + $max && $i < $maxPage) {
                $rv .= "<span class=\"plain\"> ... </span>";
                $i = $maxPage;
            }
            if ($i == $page) {
                $rv .= "<span>$i</span> ";
            } else {
                $rv .= "<a href=\"".preg_replace("/#{page}/mi", $i, $url)."\">$i</a> ";
            }
        }
        $rv .= ($page < $maxPage) ? "<a class=\"plain\" href=\"".preg_replace("/#{page}/mi", $page + 1, $url)."\">Next</a>" : "";
        $rv .= '</div>';
        return $rv;
    }
    
    public static function insertPretreat($arg) {
    
        if (is_array($arg)) {
            foreach ($arg as $key=>$value) {
                $arg[$key] = self::insertPretreat($value);
            }
            return $arg;
        } else {
            return stripslashes($arg);
        }
    }
    
    public static function printPretreat($arg) {
    
        if (is_array($arg)) {
            foreach ($arg as $key=>$value) {
                $arg[$key] = self::printPretreat($value);
            }
            return $arg;
        } else {
            return htmlspecialchars($arg);
        }
    }
    
    public static function removeDir($dirName) {
    
        if (!is_dir($dirName)) {
            return false;
        }
        $handle = @opendir($dirName);
        while (($file = @readdir($handle)) !== false) {
            if ($file != '.' && $file != '..') {
                $dir = $dirName.DIRECTORY_SEPARATOR.$file;
                is_dir($dir) ? self::removeDir($dir) : @unlink($dir);
            }
        }
        closedir($handle);
        return rmdir($dirName);
    }
    
    public static function Fileext($filename) {
    
        return trim(substr(strrchr($filename, '.'), 1, 10));
    }
    
    public static function getUserBySerial($args) {
        global $featureManager;
        if (!is_array($args)) { //only one user's serial;
            $context = array('name'=>'serial', 'value'=>$args);
            $featureManager->apply("com.yizin.platform.user.get.by.field", $context);
            return $context['user'];
        } else { // two or more user's serial;
            $context = array('name'=>'serial', 'value'=>$args);
            $featureManager->apply("com.yizin.platform.user.get.by.field", $context);
            $result = array();
            foreach ($context['user'] as $user) {
                $result[$user['serial']] = $user;
            }
            return $result;
        }
    }
	public static function changeUserSerialToName(&$objs, $key) {
		global $featureManager;
		$userSerials = array();
		foreach($objs as $obj) {
			array_push($userSerials, $obj[$key]);
		}
	    $context = array('name'=>'serial', 'value'=>$userSerials);
	    $featureManager->apply("com.yizin.platform.user.get.by.field", $context);
	    $users = $context['user'];
		
        foreach ($objs as &$obj) {
        	$user = $users[$obj[$key]];
			$obj[$key] = $user['nickname'] == ""?$user['id']:$user['nickname'];
		}
	}
    
    public static function getPathBySerial($serial, $isURL = false) {
    
        $serial = sprintf("%09s", $serial);
        return $isURL ? substr($serial, 0, 3).'/'.substr($serial, 3, 3).'/'.substr($serial, 6, 3).'/' : substr($serial,
             0, 3).DIRECTORY_SEPARATOR.substr($serial, 3, 3).DIRECTORY_SEPARATOR.substr($serial, 6, 3).DIRECTORY_SEPARATOR;
    }
    
    public static function recur_mkdirs($path, $chmod = 0777) {
    
        //$GLOBALS["dirseparator"]
        $dirs = explode(DIRECTORY_SEPARATOR, $path);
        $pos = strrpos($path, ".");
        if ($pos === false) { // note: three equal signs
            // not found, means path ends in a dir not file
            $subamount = 0;
        } else {
            $subamount = 1;
        }
        
        for ($c = 0; $c < count($dirs) - $subamount; $c++) {
            $thispath = "";
            for ($cc = 0; $cc <= $c; $cc++) {
                $thispath .= $dirs[$cc].DIRECTORY_SEPARATOR;
            }
            if (!file_exists($thispath)) {
                //print "$thispath<br>";
                mkdir($thispath, $chmod);
            }
        }
    }
    
    public static function randomArray($min, $max, $size) {
    
        $result = array();
        if ($max - $min < $size) {
            for ($m = $min; $m <= $max; $m++) {
                array_push($result, $m);
            }
        } else {
            while (count($result) < $size) {
                $n = rand($min, $max);
                if (!in_array($n, $result)) {
                    array_push($result, $n);
                }
            }
            
        }
        return $result;
    }
    
    public static function getRandomListByList($list, $size) {
    
        $result = array();
        $array = Utils::randomArray(0, count($list) - 1, $size);
        
        foreach ($array as $n) {
            array_push($result, $list[$n]);
        }
        return $result;
    }

    
    public static function cutstr($string, $length) {
        $charset = 'utf-8';
        
        $result = array();
        
        if (strlen($string) <= $length) {
            return array('first'=>$string, 'second'=>'');
        }
        
        $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
        
        $strcut = '';
        if (strtolower($charset) == 'utf-8') {
            $n = $tn = $noc = 0;
            while ($n < strlen($string)) {
                $t = ord($string[$n]);
                if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1;
                    $n++;
                    $noc++;
                } elseif (194 <= $t && $t <= 223) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif (224 <= $t && $t < 239) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif (240 <= $t && $t <= 247) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif (248 <= $t && $t <= 251) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif ($t == 252 || $t == 253) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n++;
                }
                if ($noc >= $length) {
                    break;
                }
            }
            if ($noc > $length) {
                $n -= $tn;
            }
            $strcut = substr($string, 0, $n);
            $strelse = substr($string, $n);
        } else {
            for ($i = 0; $i < $length - 1; $i++) {
                $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
            }
        }
        $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
        
        $result['first'] = $strcut;
        $result['second'] = $strelse;
        
        return $result;
    }
	public static function showMessage($m) {
		return $m == ""?"":'<p class="message">'.$m.'<span class="disappear"></span></p>';
	}
	public static function showFormError($e) {
		return $e == ""?"":'<br /><strong class="error">'.$e.'</strong>';
	}
	public static function hasRight($right) {
	    global $featureManager;
	    global $currentUser;
	    $currentUser = session_getCurrentUser();
	    if (isset($currentUser)) {
	        $userContext = array("user"=>$currentUser['serial']);
	        $featureManager->apply("com.yizin.platform.role.get.by.user", $userContext);
	        $roleContext = array('role'=>$userContext['role']['serial'], 'id'=>$right);
	        $featureManager->apply("com.yizin.platform.privilege.get.by.id", $roleContext);
	        return $roleContext['allow'];
	    }
		return FALSE;
	}
}
?>
